package com.honyelchak.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.honyelchak.shortlink.admin.dao.entity.UserDO;
import com.honyelchak.shortlink.admin.dao.mapper.UserMapper;
import com.honyelchak.shortlink.admin.dto.req.UserLoginDTO;
import com.honyelchak.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.honyelchak.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.honyelchak.shortlink.admin.dto.resp.UserActualRespDTO;
import com.honyelchak.shortlink.admin.dto.resp.UserInfoRespDTO;
import com.honyelchak.shortlink.admin.dto.resp.UserRespDTO;
import com.honyelchak.shortlink.admin.service.GroupService;
import com.honyelchak.shortlink.admin.service.UserService;
import com.honyelchak.shortlink.base.common.constant.RedisCacheConstant;
import com.honyelchak.shortlink.base.common.constant.UserConstant;
import com.honyelchak.shortlink.base.common.convention.exception.ClientException;
import com.honyelchak.shortlink.base.common.convention.exception.ServiceException;
import com.honyelchak.shortlink.base.common.enums.UserErrorCodeEnum;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.honyelchak.shortlink.base.common.constant.GroupConstant.DEFAULT_GROUP_NAME;

/**
 * @author Honyelchak
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {


    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;

    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NOT_FOUND.code(), UserErrorCodeEnum.USER_NOT_FOUND);
        }
        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public UserActualRespDTO getActualUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NOT_FOUND.code(), UserErrorCodeEnum.USER_NOT_FOUND);
        }
        UserActualRespDTO result = new UserActualRespDTO();
        BeanUtils.copyProperties(userDO, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * TODO(马哥的register方法中会出现原始异常丢失的问题)
     * @param requestParam
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if (hasUsername(requestParam.getUsername())) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        // TODO 此处和马哥的写法不太一样，需验证
        if (!lock.tryLock()) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        try {
            int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
            if (insert < 0) {
                throw new ClientException(UserErrorCodeEnum.USER_SAVE_EXIST);
            }
            userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
            groupService.saveGroup(requestParam.getUsername(),DEFAULT_GROUP_NAME);
        } catch(DuplicateKeyException ex){
            throw new ClientException("用户名已存在");
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        if (isLogin(userUpdateReqDTO.getUsername(), null)) {
            throw new ClientException("用户未登录");
        }

        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getId, userUpdateReqDTO.getId());

        UserDO userDO = BeanUtil.toBean(userUpdateReqDTO, UserDO.class);
        int update = baseMapper.update(userDO, queryWrapper);
        if (update <= 0) {
            throw new ServiceException("用户更新失败");
        }
        // TODO(update之后，要更新用户的相关的信息)
    }

    @Override
    public UserInfoRespDTO login(UserLoginDTO userLoginDTO) {
        boolean contains = userRegisterCachePenetrationBloomFilter.contains(userLoginDTO.getUsername());
        if (!contains) {
            throw new ClientException(UserErrorCodeEnum.USER_NOT_FOUND);
        }
        if (isLogin(userLoginDTO.getUsername(), null)) {
            throw new ClientException("该用户已登录");
        }

        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, userLoginDTO.getUsername())
                .eq(UserDO::getPassword, userLoginDTO.getPassword())
                .eq(UserDO::getDelFlag, UserConstant.USER_DEL_FLAG);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NOT_FOUND);
        }
    String uuid = UUID.randomUUID().toString();
    String cacheKey = RedisCacheConstant.USER_TOKEN_KEY + userLoginDTO.getUsername();
        stringRedisTemplate.opsForHash().put(cacheKey, uuid, JSON.toJSON(userDO).toString());
                stringRedisTemplate.expire(cacheKey, 30L, TimeUnit.MINUTES);
                return new UserInfoRespDTO(uuid);
                }

    @Override
    public Boolean isLogin(String username, String token) {
        String cacheKey = RedisCacheConstant.USER_TOKEN_KEY + username;
        if (StringUtils.hasLength(token)) {
            return stringRedisTemplate.opsForHash().hasKey(cacheKey, token);
        }
        return stringRedisTemplate.hasKey(cacheKey);
    }

    @Override
    public void logout(String username, String token) {
        if (!isLogin(username, token)) {
            throw new ClientException("用户token不存在或用户不存在");
        }
        String cacheKey = RedisCacheConstant.USER_TOKEN_KEY + username;
        stringRedisTemplate.delete(cacheKey);
    }
}
